package com.api.gbhg.lbj.action;

import com.api.gbhg.liwenjun.VersionFlowUtil;
import com.api.gbhg.zengping.action.MoneySources;
import com.api.gbhg.zengping.common.CommonDao;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;

import static com.api.gbhg.lbj.tool.Tools.*;
import static com.api.gbhg.lbj.tool.Tools.theCentral;

/**
 * @author lbj
 * @version 1.0
 * @description: TODO 预算来源同步
 * @date 2021/3/13 16:48
 */
public class SourceAction implements Action {
    private static final Logger logger = LoggerFactory.getLogger("gbhg");
    private static String YJ ;//科目级别
    private static String XJ ;//科目下级

    @Override
    public String execute(RequestInfo requestInfo) {
        logger.info("========================项目导入预算审批节点同步明细7,8到经费来源表==============================================");

        BaseBean baseBean = new BaseBean();
        YJ = baseBean.getPropValue("Verification","yj");
        XJ = baseBean.getPropValue("Verification","xj");
        logger.info("财政拨款核批层级 YJ="+YJ+"  XJ="+XJ);

        String requestid = requestInfo.getRequestid();
        //得到明细表名
        DetailTable[] detailTables = CommonDao.getDetailTables(requestInfo);
        //当前流程表名-类似 formtable_main_22  (批量提交时这种方法获取不到主表名)requestInfo.getRequestManager().getBillTableName()
        String billTableName = requestInfo.getRequestManager().getBillTableName();
        billTableName=detailTables[0].getTableDBName().substring(0,detailTables[0].getTableDBName().indexOf("_dt1"));
        RecordSet rs = CommonDao.selectByRequestId(new RecordSet(),billTableName , requestid);
        rs.next();
        String mainid = rs.getString("id");
        String sbdw = rs.getString("sbdw");
        // 上年结转核批明细
        RecordSet recordSetS = CommonDao.selectByDetailTable(detailTables[6].getTableDBName(), mainid);
        // 当年预算核批明细
        RecordSet recordSetD = CommonDao.selectByDetailTable(detailTables[7].getTableDBName(), mainid);

        Map<String,Object>[] maps=new HashMap[recordSetS.getArray().size()+recordSetD.getArray().size()];
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);//当前年份
        int year1 = calendar.get(Calendar.YEAR) - 1;//上年年份
        int count=0;
        // 上年结转核批明细
        while (recordSetS.next()){
            int sum1 = 0;
            int sum2 = 0;
            maps[count]=new HashMap<>();
            //支出渠道
            String zcqd = recordSetS.getString("zcqd");
            //收入类型
            String srlx = recordSetS.getString("srlx");
            //功能科目_新
            String gnkm ="";
            //中央财政拨款项目
            String zyczbksr = recordSetS.getString("zyczbksr");
            //地方财政拨款项目上年结转
            String dfczbkxmsnjz = recordSetS.getString("dfczbkxmsnjz");
            if (srlx.equals("0")) {//0：中央
                if (StringUtils.isNotBlank(zyczbksr)) {
                    String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                    sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                    sum2 = Integer.parseInt(sta[1]);//表id
                    if (sum1 == Integer.parseInt(YJ)) {
                        gnkm = getSubjectsGnkm(sum2);
                    } else if (sum1 == Integer.parseInt(XJ)) {
                        gnkm = getSubjectsGnkm(getSubjectsGnkm2(sum2));
                    }
                }
            }
            if (srlx.equals("1")){//1:非中央
                RecordSet rs1 = theCentral(zcqd, year1, sbdw);
                rs1.next();
                gnkm = rs1.getString("gnkm");
            }

            //核批金额
            String hpje = recordSetS.getString("hpje");
            maps[count].put("sbdw",rs.getString("sbdw"));
            maps[count].put("nd",rs.getString("ysnd"));
            //来源类型
            maps[count].put("zcqd",zcqd);
            //功能科目
            maps[count].put("gnkm",gnkm);
            //金额
            maps[count].put("je",hpje);
            //剩余额度
            maps[count].put("syed",hpje);
            //冻结金额
            maps[count].put("djje",0);
            //预算来源类型
            maps[count].put("yslylx","上年结转核批");
            //收入类型
            maps[count].put("srlx",srlx);
            //地方财政拨款项目上年结转
            maps[count].put("dfczbkxm",dfczbkxmsnjz);
            //中央财政拨款收入
            maps[count].put("zyczbksr",zyczbksr);
            maps[count].put("lcid",requestid);
            count++;
        }

        // 当年预算核批明细
        while (recordSetD.next()){
            int sum1 = 0;
            int sum2 = 0;
            maps[count]=new HashMap<>();
            //支出渠道
            String zcqd = recordSetD.getString("zcqd");
            //收入类型
            String srlx = recordSetD.getString("srlx");
            //功能科目_新
            String gnkm = "";
            //中央财政拨款收入
            String zyczbksr = recordSetD.getString("zyczbksr");
            //地方财政拨款项目当年预算
            String dfczbkxmdnys = recordSetD.getString("dfczbkxmdnys");
            if (srlx.equals("0")) {//0：中央
                if (StringUtils.isNotBlank(zyczbksr)) {
                    String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                    sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                    sum2 = Integer.parseInt(sta[1]);//表id
                    if (sum1 == Integer.parseInt(YJ)) {
                        gnkm = getSubjectsGnkm(sum2);
                    } else if (sum1 == Integer.parseInt(XJ)) {
                        gnkm = getSubjectsGnkm(getSubjectsGnkm2(sum2));
                    }
                }
            }
            if (srlx.equals("1")){//1:非中央
                RecordSet rs1 = theCentral(zcqd, year, sbdw);
                gnkm = rs1.getString("gnkm");
            }

            //核批金额
            String hpje = recordSetD.getString("hpje");
            maps[count].put("sbdw",rs.getString("sbdw"));
            maps[count].put("nd",rs.getString("ysnd"));
            //来源类型
            maps[count].put("zcqd",zcqd);
            //功能科目
            maps[count].put("gnkm",gnkm);
            //金额
            maps[count].put("je",hpje);
            //剩余额度
            maps[count].put("syed",hpje);
            //冻结金额
            maps[count].put("djje",0);
            //预算来源类型
            maps[count].put("yslylx","当年预算核批");
            //收入类型
            maps[count].put("srlx",srlx);
            //地方财政拨款项目当年预算
            maps[count].put("dfczbkxm",dfczbkxmdnys);
            //中央财政拨款收入
            maps[count].put("zyczbksr",zyczbksr);
            maps[count].put("lcid",requestid);
            count++;
        }


        // 存储数据到经费来源表
        boolean b = storageDateToJingfeiLy(maps);
        if(!b){
            logger.info("============================项目导入预算审批节点同步明细7,8到经费来源表错误======================================");
            requestInfo.getRequestManager().setMessagecontent("项目导入预算审批节点同步明细7,8到经费来源表出现错误");
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
    /* *
     * @Author 尚展锋
     * @Description //检测Map空的key删除
     * @Date 17:31 2020/9/5
     * @Param [param]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> removeNullString(Map<String, Object> param) {
        try {
            Iterator<String> it = param.keySet().iterator();
            while (it.hasNext()) {
                Object ele = it.next();
                if (param.get(ele).toString().trim().equals("")) {
                    //hashMap.remove(ele);    //出错 修改了映射结构 影响了迭代器遍历
                    it.remove();              //用迭代器删除 则不会出错
                }
            }
            return param;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean storageDateToJingfeiLy(Map[] maps){
        boolean flag=false;
        for (int i = 0; i < maps.length; i++) {
            Map map = removeNullString(maps[i]);
            Set set = map.keySet();
            List<String> listField = new ArrayList<String>(set);
            // 上年结转
            Collection<String> valueCollection = map.values();
            List<String> valueList = new ArrayList<>(valueCollection);
            // 存储数据到经费来源表
            RecordSetTrans rst=new RecordSetTrans();
            String uf_jingfeilaiyuansql = VersionFlowUtil.getInsertSql(listField, "uf_jingfeilaiyuan");
            try {
                rst.executeUpdate(uf_jingfeilaiyuansql,valueList.toArray());
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("同步经费来源sql---->"+uf_jingfeilaiyuansql+valueCollection);
                logger.info("errorsql=="+e.toString());
                flag=false;
            }
            flag=true;
        }
        return flag;
    }
}

